import matplotlib.pyplot as plt
import math
from scipy.spatial import ConvexHull
import os
import numpy as np
from scipy.spatial.distance import pdist
import xlwt
import pandas as pd
import collections
from openpyxl.workbook import Workbook

class MALE(object):
	"""docstring for People"""
	def __init__(self, file = 'CSR0013A.txt'):
		super(MALE, self).__init__()
		self.file = file
		self.hips = None
		self.thigh = None
		with open(self.file,'r') as fp:
			self.point_x = []
			self.point_y = []
			self.point_z = []
			while True:
				line = fp.readline()
				if line == '':
					break
				data = line.split()
				self.point_x.append(float(data[0]))
				self.point_y.append(float(data[1]))
				self.point_z.append(float(data[2]))
		self.shengao = int(max(self.point_y)-min(self.point_y))
		self.touchang= int(max(self.point_y)-self.point_y[72])
		self.quganchang= self.shengao - self.touchang
		# self.shangshen_length = int(self.point_y[1154]-self.point_y[])
		# self.yaohou = int(self.point_z[35]-self.point_z[2352])
		# self.yaokuan = int(self.point_x[3800]-self.point_x[2377])
		# self.xionghou = int(self.point_z[3850]-self.point_z[2472])
		# self.xiongkuan = int(self.point_x[5666] - self.point_x[2448])
		# self.tunhou = int(self.point_z[13]-self.point_z[2246])
		# self.tunkuan = int(self.point_x[3718] - self.point_x[2270])

		self.jiankuan = int(self.point_x[4142] - self.point_x[926])
		print('self.jiankuan:',self.jiankuan)
		self.xiaotuichang = int(self.point_y[209]-min(self.point_y))
		print('self.xiaotuichang:',self.xiaotuichang)
		self.huiyinggao = int(self.point_y[1090]-min(self.point_y))
		print('self.huiyinggao:',self.huiyinggao)
		self.shoubichang = int((np.sqrt((self.point_x[2957]-self.point_x[926])**2+(self.point_y[2957]-self.point_y[926])**2+(self.point_z[2957]-self.point_z[926])**2) + np.sqrt((self.point_x[5996]-self.point_x[4142])**2+(self.point_y[5996]-self.point_y[4142])**2+(self.point_z[5996]-self.point_z[4142])**2))/2)
		print('self.shoubichang:',self.shoubichang)
		# 获取列表的第二个元素
		def takeSecond(elem):
			return elem[1]

		#腰围计算(-50到25范围内)
		yaowei_lst = []
		yaowei = []
		yaokuan = []
		yaohou = []
		yaodian =int(self.shengao *0.6+min(self.point_y))
		for delta in range(3):
			for i in range(len(self.point_y)):
				if float(yaodian-50+delta*25) < self.point_y[i] < float(yaodian-25+delta*25):
					yaowei_lst.append([self.point_x[i],self.point_z[i]])
			yaowei_lst = sorted(yaowei_lst)
			qugan = []
			flag = 0
			for i in range(len(yaowei_lst)-1):
				if yaowei_lst[i+1][0] - yaowei_lst[i][0] > 35:
					flag += 1
					if flag >= 3:
						print('error')
						break
					continue
				#获取腰中间点云
				if yaowei_lst[i+1][0] - yaowei_lst[i][0] <= 40  and flag == 1:
					qugan.append(yaowei_lst[i])
			yaokuan.append(int(max(qugan)[0] - min(qugan)[0]))
			yaohou.append(int(max(qugan, key=takeSecond)[1] - min(qugan, key=takeSecond)[1]))
			yaowei_np = np.array(qugan)
			# plt.plot(yaowei_np[:, 0], yaowei_np[:, 1], 'o')
			plt.axis('equal')
			hull = ConvexHull(yaowei_np)
			hull1 = hull.vertices.tolist()  # 要闭合必须再回到起点[0]
			hull1.append(hull1[0])
			sum = 0
			for simplex in hull.simplices:
				# plt.plot(yaowei_np[simplex, 0], yaowei_np[simplex, 1], 'k-')
				sum += np.sqrt(np.sum(np.square(np.array([yaowei_np[simplex,0][0],yaowei_np[simplex,1][0]])-np.array([yaowei_np[simplex,0][1],yaowei_np[simplex,1][1]]))))
			yaowei.append(sum)
		suoyin= yaowei.index(min(yaowei))
		# print('suoyin',suoyin)
		self.yaowei = int(min(yaowei))
		self.yaokuan = yaokuan[suoyin]
		self.yaohou = yaohou[suoyin]
		print('self.yaokuan:', self.yaokuan)
		print('self.yaohou:', self.yaohou)
		print('yaowei:',yaowei)
		print('self.yaowei:',self.yaowei)
		# plt.show()


		#臀围计算
		tunwei_lst = []
		tunwei = []
		tunkuan = []
		tunhou = []
		tundian = int(self.shengao * 0.52 + min(self.point_y))
		for delta in range(3):
			for i in range(len(self.point_y)):
				if float(tundian - 30 + delta * 20) < self.point_y[i] < float(tundian - 10 + delta * 20):
					tunwei_lst.append([self.point_x[i], self.point_z[i]])
			tunwei_lst = sorted(tunwei_lst)
			# print('tunwei_lst ',tunwei_lst )
			# tunwei_np = np.array(tunwei_lst)
			# plt.plot(tunwei_np[:, 0], tunwei_np[:, 1], 'o')
			qugan = []
			flag = 0
			for i in range(len(tunwei_lst) - 1):
				if tunwei_lst[i + 1][0] - tunwei_lst[i][0] > 45:
					flag += 1
					# print(flag)
					if flag >=3:
						print('error')
						break
					continue
				# 获取臀中间点云
				if tunwei_lst[i + 1][0] - tunwei_lst[i][0] <= 40 and flag == 1:
					qugan.append(tunwei_lst[i])
			tunkuan.append(int(max(qugan)[0] - min(qugan)[0]))
			tunhou.append(int(max(qugan, key=takeSecond)[1] - min(qugan, key=takeSecond)[1]))

			tunwei_np = np.array(qugan)
			# plt.plot(tunwei_np[:, 0], tunwei_np[:, 1], 'o')
			plt.axis('equal')
			hull = ConvexHull(tunwei_np)
			hull1 = hull.vertices.tolist()  # 要闭合必须再回到起点[0]
			hull1.append(hull1[0])
			sum = 0
			for simplex in hull.simplices:
				# plt.plot(tunwei_np[simplex, 0], tunwei_np[simplex, 1], 'k-')
				sum += np.sqrt(np.sum(np.square(
					np.array([tunwei_np[simplex, 0][0], tunwei_np[simplex, 1][0]]) - np.array(
						[tunwei_np[simplex, 0][1], tunwei_np[simplex, 1][1]]))))
			tunwei.append(sum)
		print('tunwei: ',tunwei)
		suoyin = yaowei.index(max(yaowei))
		print('suoyin', suoyin)
		self.tunwei = int(max(tunwei))
		print('self.tunwei:',self.tunwei)
		self.tunkuan = tunkuan[suoyin]
		self.tunhou = tunhou[suoyin]
		print('self.tunkuan:', self.tunkuan)
		print('self.tunhou:', self.tunhou)
		# plt.show()

		#大腿围计算
		datuiwei_lst = []
		datuiwei = []
		datuidian = int(self.shengao * 0.41+ min(self.point_y))
		for delta in range(3):
			for i in range(len(self.point_y)):
				if float(datuidian - 20 + delta * 10) < self.point_y[i] < float(datuidian - 0 + delta * 10):
					datuiwei_lst.append([self.point_x[i], self.point_z[i]])
			datuiwei_lst = sorted(datuiwei_lst)
			center = (datuiwei_lst[0][0] + datuiwei_lst[-1][0])/2
			datuiwei_lst = [point for point in datuiwei_lst if point[0] < center]
			# print('datuiwei_lst ',datuiwei_lst )
			datuiwei_np = np.array(datuiwei_lst)
			# plt.plot(tunwei_np[:, 0], tunwei_np[:, 1], 'o')
			plt.axis('equal')
			hull = ConvexHull(datuiwei_np)
			hull1 = hull.vertices.tolist()  # 要闭合必须再回到起点[0]
			hull1.append(hull1[0])
			sum = 0
			for simplex in hull.simplices:
				# plt.plot(datuiwei_np[simplex, 0], datuiwei_np[simplex, 1], 'k-')
				sum += np.sqrt(np.sum(np.square(
					np.array([datuiwei_np[simplex, 0][0], datuiwei_np[simplex, 1][0]]) - np.array(
						[datuiwei_np[simplex, 0][1],datuiwei_np[simplex, 1][1]]))))
			datuiwei.append(sum)
		print('datuiwei: ', datuiwei)
		self.datuiwei = int(max(datuiwei))
		print('self.datuiwei:',self.datuiwei)
		# plt.plot(datuiwei_np[:, 0], datuiwei_np[:, 1], 'o')
		# plt.show()

		#胸围计算
		xiongwei_lst = []
		xiongwei = []
		xiongkuan = []
		xionghou = []
		xiongdian = int(self.shengao * 0.72+ min(self.point_y))
		for delta in range(3):
			for i in range(len(self.point_y)):
				if float(xiongdian - 30 + delta * 15) < self.point_y[i] < float(xiongdian - 15+ delta * 15):
					xiongwei_lst.append([self.point_x[i], self.point_z[i]])
			xiongwei_lst = sorted(xiongwei_lst)
			center_x = int((xiongwei_lst[0][0]+xiongwei_lst[-1][0])/2)
			center_y = int((xiongwei_lst[0][1]+xiongwei_lst[-1][1])/2)
			kuan = abs(xiongwei_lst[0][0]-xiongwei_lst[-1][0])
			# print("center_x: ",center_x)
			# print("center_y: ", center_y)
			# print("kuan:",kuan)
			#分割
			temp1 = []
			temp2 = []
			temp3 = []
			temp4 = []
			for i in range(len(xiongwei_lst)):
				if xiongwei_lst[i][0] < center_x and xiongwei_lst[i][1] > center_y and i > 10:
					temp1.append(xiongwei_lst[i])
				if xiongwei_lst[i][0] < center_x and xiongwei_lst[i][1] < center_y and i>10:
					temp2.append(xiongwei_lst[i])
				if xiongwei_lst[i][0] > center_x and xiongwei_lst[i][1] > center_y and i < len(xiongwei_lst)-13:
					temp3.append(xiongwei_lst[i])
				if xiongwei_lst[i][0] > center_x and xiongwei_lst[i][1] < center_y and i < len(xiongwei_lst)-13:
					temp4.append(xiongwei_lst[i])
			temp1.sort(key = takeSecond)
			temp2.sort(key = takeSecond)
			temp3.sort(key = takeSecond)
			temp4.sort(key = takeSecond)
			#除噪点
			tmp = []
			tmp1=[]
			tmp2 = []
			tmp3 = []
			tmp4 = []
			#左上
			for i in range(len(temp1)):
				if temp1[i][0] > temp1[0][0]:
					tmp1.append(temp1[i])
			tmp1.sort(key = takeSecond)
			for i in range(len(tmp1)):
				if tmp1[i][0] > tmp1[0][0]:
					plt.scatter(tmp1[0][0],tmp1[0][1],c='y')
					tmp.append(tmp1[i])
			#左下
			for i in range(len(temp2)) :
				if temp2[i][0] > temp2[-1][0]:
					tmp2.append(temp2[i])
			tmp2.sort(key=takeSecond)
			for i in range(len(tmp2)):
				if tmp2[i][0] > tmp2[-1][0]:
					plt.scatter(tmp2[-1][0],tmp2[-1][1],c='r')
					tmp.append(tmp2[i])
			#右上
			for i in range(len(temp3)):
				if temp3[i][0] < temp3[0][0]:
					tmp3.append(temp3[i])
			tmp3.sort(key=takeSecond)
			for i in range(len(tmp3)):
				if tmp3[i][0] < tmp3[0][0]:
					plt.scatter(tmp3[0][0],tmp3[0][1],c='g')
					tmp.append(tmp3[i])
			#右下
			for i in range(len(temp4)):
				if temp4[i][0] < temp4[-1][0]:
					tmp4.append(temp4[i])
			tmp4.sort(key=takeSecond)
			for i in range(len(tmp4)):
				if tmp4[i][0] < tmp4[-1][0]:
					plt.scatter(tmp4[-1][0],tmp4[-1][1],c='b')
					tmp.append(tmp4[i])
			tmp = sorted(tmp)
			# tmp = tmp[1:-1]
			xiongkuan.append(int(max(tmp)[0] - min(tmp)[0]))
			xionghou.append(int(max(tmp, key=takeSecond)[1] - min(tmp, key=takeSecond)[1]))

			xiongwei_np = np.array(tmp)
			xiongwei_np1 = np.array(xiongwei_lst)
			# plt.plot(xiongwei_np[:, 0], xiongwei_np[:, 1], 'o')
			plt.plot(xiongwei_np1[:, 0], xiongwei_np1[:, 1],'b+')

			hull = ConvexHull(xiongwei_np)
			hull1 = hull.vertices.tolist()  # 要闭合必须再回到起点[0]
			hull1.append(hull1[0])
			sum = 0
			for simplex in hull.simplices:
				plt.plot(xiongwei_np[simplex, 0], xiongwei_np[simplex, 1], 'k-')
				sum += np.sqrt(np.sum(np.square(
					np.array([xiongwei_np[simplex, 0][0], xiongwei_np[simplex, 1][0]]) - np.array(
						[xiongwei_np[simplex, 0][1], xiongwei_np[simplex, 1][1]]))))
			xiongwei.append(sum)
		print('xiongwei:',xiongwei)
		suoyin = xiongwei.index(max(xiongwei))
		self.xiongwei = int(max(xiongwei))
		print('self.xiongwei',self.xiongwei)
		self.xiongkuan = xiongkuan[suoyin]
		self.xionghou = xionghou[suoyin]
		print('self.xiongkuan:', self.xiongkuan)
		print('self.xionghou:', self.xionghou)

		plt.title(str(self.xiongwei))
		# plt.plot(xiongwei_np[:, 0], xiongwei_np[:, 1], 'o')

		# plt.show()


if __name__ =="__main__":

	path = [[root, dirs, files] for root, dirs, files in os.walk('male_models_rebuild')][0]
	# print(path)
	aa = []
	for item in path[2]:
		aa.append(int(item[3:7]))
	path[2], aa = zip(*sorted(zip(path[2], aa)))

	print(len(path[2]))
	people = collections.OrderedDict() #有序字典
	people = {'name':[],'shengao':[],'jiankuan':[],'huiyinggao':[],'shoubichang':[],'xiongkuan':[],'xionghou':[],'xiongwei':[],'yaokuan':[],'yaohou':[],'yaowei':[],'tunkuan':[],'tunhou':[],'tunwei':[],'xiaotuichang':[],'datuiwei':[]}
	for i in range(len(path[2])):
		print(path[2][i])
		file = path[0] + '/' +path[2][i]
		male = MALE(file)
		print("****************************************")
		people['name'].append(path[2][i])
		people['shengao'].append(male.shengao)
		people['jiankuan'].append(male.jiankuan)
		people['huiyinggao'].append(male.huiyinggao)
		people['shoubichang'].append(male.shoubichang)
		people['xiongkuan'].append(male.xiongkuan)
		people['xionghou'].append(male.xionghou)
		people['xiongwei'].append(male.xiongwei)
		people['yaokuan'].append(male.yaokuan)
		people['yaohou'].append(male.yaohou)
		people['yaowei'].append(male.yaowei)
		people['tunkuan'].append(male.tunkuan)
		people['tunhou'].append(male.tunhou)
		people['tunwei'].append(male.tunwei)
		people['xiaotuichang'].append(male.xiaotuichang)
		people['datuiwei'].append(male.datuiwei)
	# print(people['shengao'])

	# 创建excel工作表
	workbook = xlwt.Workbook(encoding='utf-8')
	worksheet = workbook.add_sheet('sheet1')

	# 设置表头
	worksheet.write(0, 0, label='名字')
	worksheet.write(0, 1, label='身高')
	worksheet.write(0, 2, label='肩宽')
	worksheet.write(0, 3, label='会阴高')
	worksheet.write(0, 4, label='手臂长')
	worksheet.write(0, 5, label='胸宽')
	worksheet.write(0, 6, label='胸厚')
	worksheet.write(0, 7, label='胸围')
	worksheet.write(0, 8, label='腰宽')
	worksheet.write(0, 9, label='腰厚')
	worksheet.write(0, 10, label='腰围')
	worksheet.write(0, 11, label='臀宽')
	worksheet.write(0, 12, label='臀厚')
	worksheet.write(0, 13, label='臀围')
	worksheet.write(0, 14, label='小腿长')
	worksheet.write(0, 15, label='大腿围')
	for i,item in enumerate(people['name']):
		worksheet.write(i+1, 0, item[:-4])
	for i,item in enumerate(people['shengao']):
		worksheet.write(i+1, 1, item)
	for i,item in enumerate(people['jiankuan']):
		worksheet.write(i+1, 2, item)
	for i,item in enumerate(people['huiyinggao']):
		worksheet.write(i+1, 3, item)
	for i,item in enumerate(people['shoubichang']):
		worksheet.write(i+1, 4, item)
	for i,item in enumerate(people['xiongkuan']):
		worksheet.write(i+1, 5, item)
	for i,item in enumerate(people['xionghou']):
		worksheet.write(i+1, 6, item)
	for i,item in enumerate(people['xiongwei']):
		worksheet.write(i+1, 7, item)
	for i,item in enumerate(people['yaokuan']):
		worksheet.write(i+1, 8, item)
	for i,item in enumerate(people['yaohou']):
		worksheet.write(i+1, 9, item)
	for i,item in enumerate(people['yaowei']):
		worksheet.write(i+1, 10, item)
	for i,item in enumerate(people['tunkuan']):
		worksheet.write(i+1, 11, item)
	for i,item in enumerate(people['tunhou']):
		worksheet.write(i+1, 12, item)
	for i,item in enumerate(people['tunwei']):
		worksheet.write(i+1, 13, item)
	for i,item in enumerate(people['xiaotuichang']):
		worksheet.write(i+1, 14, item)
	for i,item in enumerate(people['datuiwei']):
		worksheet.write(i+1, 15, item)
	workbook.save('0to1480.xls')